#include "credits.h"

/* Shows the credits on an SMK bg */

// Dependency on libsmacker
#include <Smacker/smacker.h>

// Send in the externs
//extern GLuint cursor_list;
extern struct cfg_struct *cfg;
extern GLfloat aspect;
//extern int mx, my;

int credits_main()
{
    // set to 0 to run.  set to non-zero to exit and change gamestate
	int done = 0;

    // Video
    smk s;
	SDL_TimerID frame_timer;

	// Integer which holds the current frame texture
	SDL_Surface *frame = NULL;
    GLuint frame_tex;
	// Other UI textures
//	GLuint credits_tex[5];
	// Screen positioning (letterbox / pillarbox)
	GLuint xoffset, yoffset;
	float scale_x, scale_y;

    /* Go open the SMK file. */
    if (!(s = smk_open("data/video/credit.smk",SMK_MODE_MEMORY)))
    {
        /* Unable to load SMK file. Rats. */
        printf("WARNING: Unable to load data/video/credit.smk.\n");
		return GAMESTATE_MENU;
    }

    smk_enable_palette(s,1);
    smk_enable_video(s,1);

	smk_first(s);

	/* Set up all the textures we'll need for this screen. */
    frame = tex_from_smkframe(smk_get_palette(s),smk_get_video(s),smk_info_video_w(s),smk_info_video_h(s));
    if (frame == NULL)
    {
        fprintf(stderr,"WARNING: tex_from_smkframe returned NULL.\n");
        done = GAMESTATE_ERROR;
    } else {
        frame_tex = build_texture (frame, GL_LINEAR);
        SDL_FreeSurface(frame);
    }

	/* Perform a conversion for scaled items to screen coords. */
    float movie_aspect = ((float)smk_info_video_w(s)) / ((float)smk_info_video_h(s));
    if (movie_aspect > aspect) // 16:9 movie on narrow screen: match W, scale H
    {
		scale_x = (float)smk_info_video_w(s);
		scale_y = (float)smk_info_video_w(s) / aspect;
		xoffset = 0;
		yoffset = ((((float)smk_info_video_w(s) / aspect) - (float)smk_info_video_h(s)) / 2) + .5;
    }
    else // 4:3 movie on wider screen: match H, scale W
    {
		scale_x = aspect * (float)smk_info_video_h(s);
		scale_y = (float)smk_info_video_h(s);
		xoffset = ((((float)smk_info_video_h(s) * aspect) - (float)smk_info_video_w(s)) / 2) + .5;
		yoffset = 0;
    }

	/* Put us into GLOrtho mode */
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	/* Match movie resolution */
	/* This is to draw "scaled" UI elements */
	glOrtho(0.0f,scale_x,scale_y,0.0f,-1.0f,1.0f);
    glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	GLuint quad_list = glGenLists(1);
	glNewList(quad_list, GL_COMPILE);
		/* Display list for the entire movie scene. */
		glBindTexture(GL_TEXTURE_2D,frame_tex);
		glBox(xoffset,yoffset,w,h,0,0,powerOfTwo(w),powerOfTwo(h));
	glEndList();

	/* Load MUSIC */
	Mix_Music *credits_music = load_music("radio/stations/classic/music/valk");
	if(!credits_music) {
		printf("music_load(\"radio/stations/classic/music/valk\"): %s\n", Mix_GetError());
	} else {
		if(Mix_PlayMusic(credits_music, -1)==-1) {
			printf("Mix_PlayMusic: %s\n", Mix_GetError());
		}
	}

	// Start the video timer
	frame_timer = SDL_AddTimer((Uint32)((1000.0f / smk_info_fps(s)) + 0.5f), credits_next_frame, NULL);

	SDL_Event event;

	unsigned char dirty = 1;

	while (!done)
	{
		/* Check for events */
        /* Keypress skips to video 2 */
		while (SDL_PollEvent (&event))
		{
			switch (event.type)
			{
				case SDL_USEREVENT:
					dirty = 1;
					if (smk_next(s) == SMK_DONE)
					{
						// movie over, out of frames
						smk_first(s);
					}

					frame = tex_from_smkframe(smk_get_palette(s),smk_get_video(s),smk_info_video_w(s),smk_info_video_h(s));
					if (frame == NULL)
					{
						fprintf(stderr,"WARNING: tex_from_smkframe returned NULL.\n");
						done = GAMESTATE_ERROR;
					} else {
						glBindTexture(GL_TEXTURE_2D,frame_tex);
						rebuild_texture (frame_tex, frame);
						SDL_FreeSurface(frame);
					}
					break;
				case SDL_KEYUP:
					done = GAMESTATE_MENU;
					//                    done = next_gamestate;
					break;
				case SDL_MOUSEBUTTONUP:
					done = GAMESTATE_MENU;
					break;
				case SDL_QUIT:
                    done = GAMESTATE_EXIT;
					break;
				default:
					break;
			}
		}

		if (dirty) {
			/* Nuke everything */
			glClear(GL_COLOR_BUFFER_BIT);

			glCallList(quad_list);

			glEnable(GL_BLEND);
//			glCallList(credits_list);
			glDisable(GL_BLEND);

			SDL_GL_SwapBuffers();

			dirty = 0;
		}

		/* Don't run too fast */
		SDL_Delay (1);
	}

	/* shutdown frame timer */
	SDL_RemoveTimer(frame_timer);

	/* end music */
//	if (credits_click != NULL) { Mix_FreeChunk(credits_click); }
	if (credits_music != NULL) { Mix_HaltMusic(); Mix_FreeMusic(credits_music); }

    glDeleteLists(quad_list, 1);

//	glDeleteTextures( 5, credits_tex);
	glDeleteTextures( 1, &frame_tex );

	smk_close(s);

	return done;
}

